package com.lfy.modules.blog.listener;

import com.lfy.modules.blog.cache.ArticleDetailCache;
import com.lfy.modules.blog.cache.HomeCache;
import com.lfy.modules.blog.domain.event.ClearHomeArticleCacheEvent;
import com.lfy.modules.blog.domain.event.ClearWebArticleDetailEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.concurrent.TimeUnit;

/**
 * 清空首页缓存处理器
 *
 * @author <a href="https://www.lvfeiy.top">吕飞扬</a>
 * @date 2024/5/13 19:05
 */
@Component
@Slf4j
public class ClearArticleListener {
    @TransactionalEventListener(classes = {ClearHomeArticleCacheEvent.class},fallbackExecution = true,phase = TransactionPhase.AFTER_COMMIT)
    @Async("mainThreadPool")
    public void clearHomeCache(ClearHomeArticleCacheEvent event) {
        log.info("清空首页缓存");
        Long userId = event.getUserId();
        HomeCache.remove(userId);
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        HomeCache.remove(userId);
    }
    @TransactionalEventListener(classes = {ClearWebArticleDetailEvent.class},fallbackExecution = true,phase = TransactionPhase.AFTER_COMMIT)
    @Async("mainThreadPool")
    public void clearWebArticleDetailCache(ClearWebArticleDetailEvent event) {
        log.info("清空文章详情缓存");
        Long articleId = event.getArticleId();
        ArticleDetailCache.remove(articleId);
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ArticleDetailCache.remove(articleId);

    }
}
